package com.dahai.gameinfo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dahai.gameinfo.HttpRequest;
import com.dahai.gameinfo.ResultData;
import com.dahai.gameinfo.model.ListClass;
import com.dahai.gameinfo.model.ListData;
import com.dahai.gameinfo.model.UserSelect;
import com.dahai.gameinfo.model.Userinfo;
import com.dahai.gameinfo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.Date;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@RestController()
public class HelloController {

    @Autowired
    DemoService service;

    @GetMapping("/list/getGameList")
    public ResultData getGameList(@RequestParam("clazz") int clazz) {
        ResultData result = new ResultData();
        List<ListData> list = service.getListByClass(clazz);
        list.sort((o1, o2) -> o2.getHot() - o1.getHot());
        result.setList(list);
        return result;
    }

    @GetMapping("/list/getHomeList")
    public ResultData getHome() {
        ResultData result = new ResultData();
        List<ListData> list = service.getHome();
        list.sort((o1, o2) -> o2.getHot() - o1.getHot());
        result.setList(list);
        return result;
    }

    @GetMapping("/list/getClassList")
    public ResultData getClassData() {
        ResultData result = new ResultData();
        List<ListClass> list = service.getClassType();
        list.sort(Comparator.comparingInt(ListClass::getId));
        result.setList(list);
        return result;
    }

    @PostMapping("/list/addSelect")
    public ResultData selectData(@RequestBody UserSelect clazz) {
        ResultData result = new ResultData();
        if (clazz.getUserid() == 0) {
            result.setState(-1);
            result.setMessage("请销毁重新加载小程序再试");
            return result;
        }
        if (clazz.getGameId().isEmpty()) {
            result.setState(-1);
            result.setMessage("请选择游戏后再保存");
            return result;
        }
        clazz.setDate(new Date(System.currentTimeMillis()));
        service.saveSelect(clazz);
        result.setObject(clazz);
        return result;
    }

    @GetMapping("/list/getUserinfo")
    public ResultData getUserinfo(@RequestParam("openid") String code) {
        return getOpenId(code, 3);
    }

    private ResultData getOpenId(String code, int retryCode) {
        ResultData result = new ResultData();
        String wxUrl = "https://api.weixin.qq.com/sns/jscode2session";

        String url = wxUrl + "?"
                + "appid=wx01db1fa1843c0d83"
                + "&secret=67a4a76dd457707f390e5eab9037dbbb"
                + "&js_code=" + code
                + "&grant_type=authorization_code";
        Userinfo userinfo = new Userinfo();
        userinfo.setDate(new Date(System.currentTimeMillis()));
        try {
            String json = HttpRequest.httpGet(url);
            JSONObject jsonObject = JSON.parseObject(json);
            String openid = jsonObject.getString("openid");
            String session_key = jsonObject.getString("session_key");
            List<Userinfo> userInfo = service.getUserInfo(openid);
            if (userInfo.size() > 0) {
                result.setObject(userInfo.get(0));
                return result;
            } else {
                userinfo.setOpenid(openid);
                userinfo.setSessionKey(session_key);
                service.saveOrUpdateUserInfo(userinfo);
                Thread.sleep(1000);
                userInfo = service.getUserInfo(openid);
                if (userInfo.size() > 0) {
                    result.setObject(userInfo.get(0));
                    return result;
                }
                if (retryCode > 0) {
                    getOpenId(code, --retryCode);
                } else {
                    result.setState(-1);
                    result.setMessage("请稍后再试");
                    return result;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (retryCode > 0) {
                getOpenId(code, --retryCode);
            } else {
                result.setState(-1);
                result.setMessage(e.getMessage());
                return result;
            }
        }
        result.setState(-1);
        result.setMessage("请稍后再试");
        return result;
    }

    @GetMapping("/list/getUserSelect")
    public ResultData getUserSelect(@RequestParam("userid") int userid) { //
        ResultData result = new ResultData();
        List<UserSelect> list = service.getUserSelectById(userid);
        list.sort((o1, o2) -> o2.getId() - o1.getId());
        result.setList(list);
        return result;
    }

    @GetMapping("/list/getSelectDetail")
    public ResultData getSelectDetail(@RequestParam("gameId") String gameId) {
        ResultData result = new ResultData();
        List<ListData> list = new ArrayList<>();
        if (gameId!=null) {
            String[] split = gameId.split(",");
            for (String s : split) {
                if (s.isEmpty()) {
                    continue;
                }
                List<ListData> listById = service.getListById(Integer.parseInt(s));
                list.addAll(listById);
            }
        }
        result.setList(list);
        return result;
    }

    @GetMapping("/list/searchGame")
    public ResultData searchGame(@RequestParam("title") String title) {
        ResultData result = new ResultData();
        if (title!=null) {
            List<ListData> list = service.searchGame("%"+title+"%");
            result.setList(list);
            result.setCount(list.size());
        }
        return result;
    }
}
